
import { reactive, ref } from "vue";


//函数防抖    不立即执行函数，在规定时间之后执行函数 interval(规定时间)
/**
 * @fn 执行函数
 * @interval  防抖时长
*/
export function debounce(fn, interval) {
  let timer = null;
  return function () {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fn.apply(this, arguments);
      timer = null
    }, interval)
  }
}

/**
 * 分页查询
 */
export function usePagingQuery(onGetList, params = {}) {
  let _pageNo = 1,
    _pageSize = 10

  const pagingInfo = reactive({ list: [], total: 0, hasMore: true, loading: false, refreshLoading: false })
  const paramsInfo = ref(params)
  function getList() {
    return onGetList({ page: _pageNo, pageSize: _pageSize, ...paramsInfo.value }).then((res) => {
      pagingInfo.loading = false
      pagingInfo.refreshLoading = false
      pagingInfo.list = _pageNo === 1 ? (res?.data || []) : pagingInfo.list.concat(res?.data || [])
      pagingInfo.total = res?.total || 0
      pagingInfo.hasMore = !(pagingInfo.list.length >= (res?.total || 0))
    }).catch(() => {
      pagingInfo.loading = false
      pagingInfo.refreshLoading = false
    })
  }
  function initPagingQuery(refreshLoading = true) {
    pagingInfo.refreshLoading = refreshLoading
    pagingInfo.hasMore = true
    pagingInfo.loading = true
    pagingInfo.list = []
    _pageNo = 1
    return getList()
  }
  function loadPagingMore() {
    if (!pagingInfo.hasMore) return Promise.reject()
    if (pagingInfo.list <= 0) return Promise.reject()
    _pageNo += 1
    pagingInfo.loading = true
    return getList()
  }
  return {
    pagingInfo,
    paramsInfo,
    initPagingQuery,
    loadPagingMore
  }
}
